import axios from "axios";
import {notification, message} from "antd";
import storage from "store";
import {ACCESS_TOKEN} from "../store/mutation-types";
import { Logout } from "@/store/modular/user";

const service = axios.create({
    baseURL:process.env.REACT_APP_BASE_API,
    timeout: 6000 // 请求超时时间
})


// 异常拦截处理器
const errorHandler = (error) => {
    if (error.response) {
        const data = error.response.data
		const token = storage.get(ACCESS_TOKEN)
        // 从 localstorage 获取 token
        if (error.response.status === 403) {
            notification.error({
                message: 'Forbidden',
                description: data.message
            })
        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            notification.error({
                message: 'Unauthorized',
                description: 'Authorization verification failed'
            })
			if (token) {
				window.location.reload()
				//Logout(token)
				// setTimeout(() => {
				//   window.location.reload()
				// }, 1500)
			}
        }
    }
    return Promise.reject(error)
}

//请求前拦截操作
service.interceptors.request.use(config => {
    const token = storage.get(ACCESS_TOKEN)
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (token) {
        config.headers['Authorization'] = token
    }
    return config
}, errorHandler)

//响应拦截
// request.interceptors.response.use(response => {
//     if (Object.keys(response.data).length === 0){
//         return response
//     }
//     if (response.data.code !== 200) {
//         message.error(response.data.message)
//         // 登录失效
//         if (response.data.code === 202) {
//             window.location.href = '/user/login'
//         }
//         return Promise.reject(new Error(response.data.message))
//     } else {
//         return response.data
//     }
// }, errorHandler)

service.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

export default service
